/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GestionPaginas;

import almacenamiento.Atributo;
import almacenamiento.GestorIOPagina;
import almacenamiento.IdentificadorPagina;
import almacenamiento.IdentificadorTupla;
import almacenamiento.Pagina;
import almacenamiento.Relacion;
import almacenamiento.Tupla;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Usuario
 */
public class JFrameGestionPaginas extends javax.swing.JFrame {
String nombreArchivo = "relacionpagina.dat";
    List<Atributo> attrs;
    Relacion rel;
    DefaultTableModel modelotabla;
    Random rn = new Random();
    int nroPaginas;
    /**
     * Creates new form JFrameGestionPaginas
     */
    public JFrameGestionPaginas() {
        initComponents();
        PonerCabeceraTabla();
    }
 private void PonerCabeceraTabla(){
        try {
            attrs = new ArrayList<Atributo>();
        attrs.add(new Atributo("Caracter", Character.class));
        attrs.add(new Atributo("Byte", Byte.class));
        attrs.add(new Atributo("Short", Short.class));
        attrs.add(new Atributo("Integer", Integer.class));
        attrs.add(new Atributo("Long", Long.class));
        attrs.add(new Atributo("Float", Float.class));
        attrs.add(new Atributo("Double", Double.class));
        attrs.add(new Atributo("String", String.class));        
        rel = new Relacion(attrs);
        String [] encabezado = new String[rel.getAtributos().size() +1];        
        //los encabezados son dinamicos
        encabezado[0] ="Nro";
        for (int i = 1; i < encabezado.length; i++) {
            encabezado[i] = rel.getAtributo(i- 1).getNombre();
        }
        modelotabla = new DefaultTableModel(encabezado, 0);
        jTable1.setModel(modelotabla);
        } catch (Exception e) {
        }
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_paginas2 = new javax.swing.JLabel();
        lbl_paginas1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lbl_paginas3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        btn_Nro_Paginas = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lbl_paginas = new javax.swing.JLabel();
        btn_Listar_Tuplas = new javax.swing.JButton();
        btn_AgregarTuplas = new javax.swing.JButton();
        btn_Salir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbl_paginas2.setBackground(new java.awt.Color(255, 204, 0));
        lbl_paginas2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lbl_paginas2.setForeground(new java.awt.Color(102, 102, 255));
        lbl_paginas2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_paginas2.setText("3");

        lbl_paginas1.setBackground(new java.awt.Color(255, 204, 0));
        lbl_paginas1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lbl_paginas1.setForeground(new java.awt.Color(102, 102, 255));
        lbl_paginas1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_paginas1.setText("1");

        jLabel2.setText("Agrega tuplas de manera aleatoria, y añade paginas según sea el caso");

        lbl_paginas3.setBackground(new java.awt.Color(255, 204, 0));
        lbl_paginas3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lbl_paginas3.setForeground(new java.awt.Color(102, 102, 255));
        lbl_paginas3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_paginas3.setText("2");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setBackground(new java.awt.Color(255, 204, 0));
        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(102, 102, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Aplicación con Páginas");

        btn_Nro_Paginas.setText("Nro Páginas");
        btn_Nro_Paginas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_Nro_PaginasActionPerformed(evt);
            }
        });

        jLabel3.setText("Se puede ver también en la consola...");

        lbl_paginas.setBackground(new java.awt.Color(255, 204, 0));
        lbl_paginas.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lbl_paginas.setForeground(new java.awt.Color(102, 102, 255));
        lbl_paginas.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        btn_Listar_Tuplas.setText("Listar Tuplas");
        btn_Listar_Tuplas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_Listar_TuplasActionPerformed(evt);
            }
        });

        btn_AgregarTuplas.setText("Agregar tuplas Aleatoriamente");
        btn_AgregarTuplas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_AgregarTuplasActionPerformed(evt);
            }
        });

        btn_Salir.setText("Salir");
        btn_Salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_SalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbl_paginas1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_AgregarTuplas, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(41, 41, 41)
                                .addComponent(lbl_paginas3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_Listar_Tuplas, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(69, 69, 69)
                                .addComponent(lbl_paginas2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_Nro_Paginas, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lbl_paginas, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(146, 146, 146)
                                .addComponent(btn_Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(31, 31, 31)
                                .addComponent(jLabel3))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1090, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbl_paginas, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btn_AgregarTuplas, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn_Nro_Paginas, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn_Listar_Tuplas, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(lbl_paginas1))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(5, 5, 5)
                            .addComponent(lbl_paginas2))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(3, 3, 3)
                            .addComponent(lbl_paginas3)))
                    .addComponent(btn_Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(12, 12, 12)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_Nro_PaginasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_Nro_PaginasActionPerformed
        try {
            lbl_paginas.setText(String.valueOf(nroPaginas));


        } catch (Exception e) {
        }

    }//GEN-LAST:event_btn_Nro_PaginasActionPerformed

     private char GenerarCaracter(){
        String a ="qwertyuiopasdfghjklzxcvbnm";
        return a.charAt(rn.nextInt(a.length()));
    }
    private Byte GenerarByte(){
        Integer a =  rn.nextInt(50);
       Object o = (Object)a;
       return new Byte(o.toString());
    }
    private Short GenerarShort(){
        Integer a =  rn.nextInt(32768);
       Object o = (Object)a;
       return new Short(o.toString());
    }
    private int GenerarEntero(){
        return rn.nextInt();
    }
    private long GenerarLong(){
        return rn.nextLong();
    }
    private float GenerarFloat(){
        return rn.nextFloat();
    }
    private double GenerarDouble(){
        return rn.nextDouble();
    }
    private String GenerarCadena(){
        int longitudCadena = rn.nextInt(40)+1;
        String q = "";
        for (int i = 0; i < longitudCadena; i++) {
           Character x = GenerarCaracter();
           q += x.toString();
        }
        return q;
    }
    private Tupla GenerarTupla(int i){
        List<Comparable> v = new ArrayList<Comparable>();
        v.add(GenerarCaracter());
        v.add(GenerarByte());
        v.add(GenerarShort());
        v.add(GenerarEntero());
        v.add(GenerarLong());
        v.add(GenerarFloat());
        v.add(GenerarDouble());
        v.add(GenerarCadena());

        return  new Tupla(new IdentificadorTupla(nombreArchivo, i), v);
    }
    
    private void MostrarTupla(Tupla t){
        Object [] o = new Object[modelotabla.getColumnCount()];
        o[0] = t.getIdTupla().getNumero();        
        for (int i = 1; i < modelotabla.getColumnCount(); i++) {
            Comparable c= t.getValor(i-1);
            o[i] = c.toString();
        }
        modelotabla.addRow(o);
    }
    
    private void btn_Listar_TuplasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_Listar_TuplasActionPerformed
        try {
            modelotabla.setNumRows(0);
            RandomAccessFile raf = new RandomAccessFile(nombreArchivo, "r");
            System.out.println("leyendo pagina...");
            int nroPagina = 0;
            while (true) {
                Pagina pagina1 = GestorIOPagina.leerPagina(rel, new IdentificadorPagina(nombreArchivo, nroPagina), raf);
                int nroTuplas = pagina1.getNumeroDeTuplas();
                for (int i = 0; i < nroTuplas; i++) {
                    Tupla t = pagina1.recuperarTupla(i);
                    MostrarTupla(t);
                }
                nroPaginas = nroPagina;
                nroPagina++;
                //System.out.println(pagina1);
                if (false) {
                    break;
                }
            }
            nroPaginas = nroPagina;
            try {
                raf.close();
            } catch (IOException ex) {
                //Logger.getLogger(JFrameGestionPaginas.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            //Logger.getLogger(JFrameGestionPaginas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btn_Listar_TuplasActionPerformed

    private void btn_AgregarTuplasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AgregarTuplasActionPerformed
        try {
            int nroTuplas = rn.nextInt(8000);
            //int nroTuplas = 5000;
            int nroPagina = 0;
            IdentificadorPagina pid1 = new IdentificadorPagina(nombreArchivo, nroPagina);
            RandomAccessFile raf = new RandomAccessFile(nombreArchivo, "rw");
            Pagina p = new Pagina(rel, pid1);
            for (int i = 0; i < nroTuplas; i++) {

                Tupla t = GenerarTupla(i);
                //System.out.println(t);
                if (p.hayEspacio(t)) {
                    p.adicionarTupla(t);
                } else {
                    GestorIOPagina.escribirPagina(raf, p);
                    System.out.println(p.toString());
                    nroPagina++;
                    nroPaginas = nroPagina;
                    pid1 = new IdentificadorPagina(nombreArchivo, nroPagina);
                    p = new Pagina(rel, pid1);

                }
            }
            raf.close();
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
            e.printStackTrace(System.err);
        }
    }//GEN-LAST:event_btn_AgregarTuplasActionPerformed

    private void btn_SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btn_SalirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameGestionPaginas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameGestionPaginas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameGestionPaginas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameGestionPaginas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameGestionPaginas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_AgregarTuplas;
    private javax.swing.JButton btn_Listar_Tuplas;
    private javax.swing.JButton btn_Nro_Paginas;
    private javax.swing.JButton btn_Salir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbl_paginas;
    private javax.swing.JLabel lbl_paginas1;
    private javax.swing.JLabel lbl_paginas2;
    private javax.swing.JLabel lbl_paginas3;
    // End of variables declaration//GEN-END:variables
}
